package cn.yzfy.service.impl;

import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.yzfy.common.constant.RoleConstant;
import cn.yzfy.common.exception.UserSafeException;
import cn.yzfy.common.model.dto.LoginInputDTO;
import cn.yzfy.common.model.dto.LoginOutputDTO;
import cn.yzfy.common.model.entity.ResourcesEntity;
import cn.yzfy.common.model.entity.RoleResourcesEntity;
import cn.yzfy.common.model.entity.UserEntity;
import cn.yzfy.common.model.entity.UserRoleEntity;
import cn.yzfy.common.model.vo.AuthenticationUserDetailVO;
import cn.yzfy.common.model.vo.ResourcesTreeVO;
import cn.yzfy.common.util.RequestUtil;
import cn.yzfy.common.util.UserAgentInfo;
import cn.yzfy.orm.mapper.*;
import cn.yzfy.service.IAuthService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 一朝风月
 * @date 2025/9/11 20:35
 * @Code 面向注解面向卿，终无解释再无你
 * @description 鉴权服务实现类
 */
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements IAuthService {
    private final ResourcesMapper resourcesMapper;
    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final UserRoleMapper userRoleMapper;
    private final RoleResourcesMapper roleResourcesMapper;

    /**
     * 获取当前用户的权限
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<ResourcesEntity> queryPermissionsList(Long userId) {
        if (StpUtil.getRoleList().contains(RoleConstant.SUPER_ADMIN_CODE)) {
            return resourcesMapper.selectList(null);
        }
        //获取所有UserRole的id[]
        List<Long> userRoleIds = userRoleMapper.selectList(
                        Wrappers.<UserRoleEntity>lambdaQuery().eq(UserRoleEntity::getUserId, userId))
                 .stream()
                .map(UserRoleEntity::getRoleId)
                .toList();
        if (userRoleIds.size() > 0 | userRoleIds.isEmpty()) {
            return new ArrayList<>();
        }
        //通过所有id获取角色权限集合吧
        List<Long> roleResourcesList = roleResourcesMapper.selectList(
                        Wrappers.<RoleResourcesEntity>lambdaQuery().in(RoleResourcesEntity::getRoleId, userRoleIds))
                .stream()
                .map(RoleResourcesEntity::getResourcesId)
                .toList();
        // 角色没有任何权限资源，返回空列表
        if (roleResourcesList.size() > 0 | roleResourcesList.isEmpty()) {
            return new ArrayList<>();
        }
        // 根据权限资源ID列表查询具体的权限资源信息
        return resourcesMapper.selectList(
                Wrappers.<ResourcesEntity>lambdaQuery().in(ResourcesEntity::getId, roleResourcesList));
    }


    @Override
    public List<ResourcesTreeVO> queryPermissionsTree() {
        return null;
    }

    @Override
    public String captcha() {
        return null;
    }

    @Override
    public LoginOutputDTO login(LoginInputDTO inputDTO, HttpServletRequest request) {

        // 获取用户信息
        UserEntity loginUser = userMapper.selectOne(
                Wrappers.<UserEntity>lambdaQuery().eq(UserEntity::getAccount, inputDTO.getAccount()));

        // 判断账号有效性
        if (null == loginUser) {
            throw new UserSafeException("账号不存在", 430);
        }

        // 输入的密码
        String inputPwd =
                DigestUtil.sha256Hex(inputDTO.getPassword() + loginUser.getSalt(), CharsetUtil.UTF_8);

        // 比对密码
        if (!StrUtil.equals(inputPwd, loginUser.getPassword())) {
            throw new UserSafeException("账号或密码错误", 420);
        }

        // 解析User-Agent的信息
        String header = request.getHeader("User-Agent");
        UserAgentInfo userAgentInfo = RequestUtil.parseUserAgent(header);
        // sa-token 登录 并设置扩展参数, 通过StpUtil.getExtra("user");获取扩展参数
        StpUtil.login(loginUser.getId(), SaLoginConfig
                .setDevice("PC")
                .setExtra("device", userAgentInfo.getOs() + " " + userAgentInfo.getBrowser())
                .setExtra("id", loginUser.getId())
                .setExtra("username", loginUser.getUsername())
                .setExtra("account", loginUser.getAccount())
                .setExtra("phone", loginUser.getPhone())
                .setExtra("user", loginUser)
        );

        // 获取token信息
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

        return LoginOutputDTO
                .builder()
                .accessToken(tokenInfo.getTokenValue())
                .id(loginUser.getId())
                .account(loginUser.getAccount())
                .avatarUrl(loginUser.getAvatarUrl())
                .username(loginUser.getUsername())
                .gender(loginUser.getGender())
                .phone(loginUser.getPhone())
                .build();
    }

    @Override
    public void logout() {

    }

    @Override
    public AuthenticationUserDetailVO authenticationUserDetail() {
        return null;
    }
}
